package com.example.javabasic.thread.classtwo.threadlocal.demo5;

import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

public class ConsumerThread extends Thread {
    private final MessageQueue messageQueue;
    //随机数
    private static final Random random = new Random(System.currentTimeMillis());
    //计数器
    private  final AtomicInteger counter = new AtomicInteger(0);

    public ConsumerThread(MessageQueue messageQueue, String name) {
        super("consumer" + name);
        this.messageQueue = messageQueue;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Message take = messageQueue.take();
                counter.getAndIncrement();
                String data = take.getData();
                System.out.println(Thread.currentThread().getName() + "消费者消费->" + data);
                Thread.sleep(random.nextInt(500));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    //查看这个线程消费了多少次
    public int getConsumerNum() {
        return this.counter.get();
    }

}
